package com.jianshuge.zxing.activity;

import java.io.IOException;
import java.util.Vector;

import com.jianshuge.app.R;
import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.bean.DoubanBook;
import com.jianshuge.app.bean.MyResult;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.jianshuge.zxing.camera.CameraManager;
import com.jianshuge.zxing.decoding.CaptureActivityHandler;
import com.jianshuge.zxing.decoding.InactivityTimer;
import com.jianshuge.zxing.view.ViewfinderView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.inputmethod.InputMethodManager;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class CaptureActivity extends Activity implements Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;

	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	private ImageView mbackbutton;
	private ImageView btnFlashIv;
	
	private ProgressDialog mMyProgress;
	
	private TextView mReturn;
	private TextView mAddToBooklist;
	private TextView mAddToFavorite;
	private String douban_subject_id = null;

	private LinearLayout book_frame;
	
	private Handler mHandler;
	private Handler mdoubanHandler;
	
	private int cur_booklist_id;
	private int cur_book_id = -1;
	
	public ImageView book_image;  
	private TextView book_title;
	private TextView book_author;
	private TextView book_rating;
	private TextView book_pubdate;
	private TextView book_publisher;
	private TextView book_isbn;
	private ProgressBar mProgress;
	
	private ViewSwitcher mFootViewSwitcher;
	private EditText mFootEditer;
	private Button mFootPubcomment;	
	private InputMethodManager imm;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.capturez);
		
		
		cur_booklist_id = getIntent().getIntExtra("booklist_id", 0);
		
		mbackbutton = (ImageView)findViewById(R.id.back_button);
		mbackbutton.setOnClickListener(UIHelper.finish(this));
//		btnFlashIv  = (ImageView)findViewById(R.id.btnFlashIv);
	
		book_frame = (LinearLayout)findViewById(R.id.bookitem_listitem_book_frame);
		book_frame.setVisibility(View.GONE);
		
		book_image = (ImageView)findViewById(R.id.bookitem_listitem_book_image);
		book_title = (TextView)findViewById(R.id.bookitem_listitem_book_title);
		book_author = (TextView)findViewById(R.id.bookitem_listitem_author);
		book_publisher = (TextView)findViewById(R.id.bookitem_listitem_publisher);
		book_pubdate = (TextView)findViewById(R.id.bookitem_listitem_pubdate);
		book_isbn = (TextView)findViewById(R.id.bookitem_listitem_isbn);
		book_rating = (TextView)findViewById(R.id.bookitem_listitem_douban_rating);
		mProgress   = (ProgressBar)findViewById(R.id.topbar_progress);
		mProgress.setVisibility(View.GONE);
		
		mdoubanHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				if (msg.what == 1) {
					MyResult res = (MyResult) msg.obj;
					if (res.OK()) {
						cur_book_id = Integer.parseInt(res.getExtraCode());
						UIHelper.ToastMessage(CaptureActivity.this, res.getErrorMessage());
					}
				} else {					
					((AppException) msg.obj).makeToast(CaptureActivity.this);
				}
			}
		};
		
		mHandler = new Handler() {
	
			public void handleMessage(Message msg) {
				
				if (msg.what == 1 && msg.obj != null) {
					DoubanBook doubanbook = (DoubanBook) msg.obj;
					
					String book_image_url = doubanbook.getImageUrl();
					//String small_img_url = book_image_url.replace("mpic", "spic");
					if(book_image_url.endsWith("portrait.gif") || StringUtils.isEmpty(book_image_url)){
						book_image.setImageResource(R.drawable.default_book_pic);
					}else{
					//	bmpManager.loadBitmap(book_image_url, book_image);
						UIHelper.showUserFace(book_image, book_image_url);
					}

					book_title.setText("书名： " +  doubanbook.getTitle() );
					book_author.setText("作者： " + doubanbook.getAuthor());
					book_publisher.setText("出版社： " + doubanbook.getPublisher());
					book_pubdate.setText("出版日期：" + doubanbook.getPubdate());
					book_isbn.setText("ISBN： " + doubanbook.getIsbn());
					book_rating.setText("豆瓣评分： " + doubanbook.getRating());
					
					douban_subject_id = doubanbook.getSubjectId();
					saveDoubanBookThread(douban_subject_id, mdoubanHandler, true);
					
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(CaptureActivity.this);
				}
				mProgress.setVisibility(View.GONE);
			}
		};
		
		mReturn  		= (TextView)findViewById(R.id.btn_cancel_scan);
		mReturn.setOnClickListener(UIHelper.finish(this));
		mAddToBooklist	= (TextView)findViewById(R.id.btn_addto_booklist);
		mAddToFavorite	= (TextView)findViewById(R.id.btn_addto_favorite);
		mAddToFavorite.setOnClickListener(favoriteClickListener);
		
		
    	imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	
    	mFootViewSwitcher = (ViewSwitcher)findViewById(R.id.blog_detail_foot_viewswitcher);
    	mFootPubcomment = (Button)findViewById(R.id.blog_detail_foot_pubcomment);
    	mFootPubcomment.setOnClickListener(commentpubClickListener);

    	mAddToBooklist.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mFootViewSwitcher.showNext();
				mFootEditer.setVisibility(View.VISIBLE);
				mFootEditer.requestFocus();
				mFootEditer.requestFocusFromTouch();
			}
		});
    	mFootEditer = (EditText)findViewById(R.id.blog_detail_foot_editer);
    	mFootEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){  
					imm.showSoftInput(v, 0);  
		        }  
		        else{  
		            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
		        }  
			}
		}); 
    	mFootEditer.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if(mFootViewSwitcher.getDisplayedChild()==1){
						mFootViewSwitcher.setDisplayedChild(0);
						mFootEditer.clearFocus();
						mFootEditer.setVisibility(View.GONE);
					}
					return true;
				}
				return false;
			}
		});
    			
		// CameraManager
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);


	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	public void handleDecode(Result obj, Bitmap barcode) {
		inactivityTimer.onActivity();
		viewfinderView.drawResultBitmap(barcode);
		playBeepSoundAndVibrate();
		
		String BarcodeFormat = obj.getBarcodeFormat().toString();
		if( BarcodeFormat == "QR_CODE" ) {
			return;
		}
		
		if( BarcodeFormat == "EAN_13" ) {		
			String isbn = obj.getText();
			this.loadDoubanBookThread(isbn, mHandler, true);
			book_frame.setVisibility(View.VISIBLE);
		}
	}
	
	private void loadDoubanBookThread(final String isbn, final Handler handler, final boolean isRefresh){  
		
		mProgress.setVisibility(View.VISIBLE);
		new Thread(){
			public void run() {
				
				Message msg = new Message();				
				try {
					
					DoubanBook doubanbook = ((AppContext)getApplication()).getDoubanBookByIsbn(isbn, isRefresh);
					msg.what = 1;
					msg.obj = doubanbook;
	            
				} catch (AppException e) {
					
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            
				}
				
                handler.sendMessage(msg);
			}
			
		}.start();
		
	} 
	
	private void  saveDoubanBookThread(final String subject_id, final Handler handler, final boolean isRefresh){  

		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					
					MyResult res = ((AppContext)getApplication()).saveDoubanBook(subject_id, isRefresh);
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
				}
				
				handler.sendMessage(msg);
			}
			
		}.start();
		
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};
	
	
	private View.OnClickListener commentpubClickListener = new View.OnClickListener(){
		
		public void onClick(View v) {
			final String content = mFootEditer.getText().toString();
			
			if(StringUtils.isEmpty(content)) {
				UIHelper.ToastMessage(v.getContext(), "推荐理由不能为空");
				return;
			}
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "发布中···",true,true); 
			
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();
					
					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						UIHelper.ToastMessage(CaptureActivity.this, res.getErrorMessage());
						if (res.OK()) {
							Intent intent = new Intent();
							intent.putExtra("message", res.getErrorMessage());
							setResult(RESULT_OK, intent);
							finish();
						}
					} else {					
						((AppException) msg.obj).makeToast(CaptureActivity.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
						
						AppContext ac = (AppContext)getApplication();
						final int uid = ac.getLoginUid();
						if( cur_book_id != -1)
							res = ac.addBookResult(uid, cur_booklist_id, cur_book_id, content);
							
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();
		}
	};

	
	private View.OnClickListener favoriteClickListener = new View.OnClickListener(){
		
		public void onClick(View v) {
			
			if ( douban_subject_id == null ) {
				return;
			}
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "加载中···", true, true); 

			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();

					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						if (res.OK()) {
							UIHelper.ToastMessage(CaptureActivity.this, res.getErrorMessage());
						}
					
					} else {					
						((AppException) msg.obj).makeToast(CaptureActivity.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
						
						AppContext ac = (AppContext)getApplication();
						final int uid = ac.getLoginUid();
						//res = ac.scanFavorite(uid, douban_subject_id);
						if( douban_subject_id != null)
							res = ac.scanFavorite(uid, douban_subject_id);
							
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();
		}
	};

}